import os
import sys
import threading
import tkinter as tk
from tkinter import filedialog, scrolledtext
from create_plan_search import start_sub_account_url


class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.master.title("自动创建计划-搜索推广")

        # 设置窗口大小
        window_width = 600
        window_height = 400

        # 获取屏幕尺寸以计算布局，使窗口居中
        screen_width = self.master.winfo_screenwidth()
        screen_height = self.master.winfo_screenheight()

        # 计算居中位置
        x_coordinate = int((screen_width / 2) - (window_width / 2))
        y_coordinate = int((screen_height / 2) - (window_height / 2))

        # 设置窗口位置和大小
        self.master.geometry(f"{window_width}x{window_height}+{x_coordinate}+{y_coordinate}")

        self.pack(padx=10, pady=10)
        self.create_widgets()

        # 存储用户选择的文件路径和并发数
        self.file_path = ""
        self.concurrency = 3

    def create_widgets(self):
        # 文件选择框
        self.file_frame = tk.Frame(self)
        self.file_frame.pack(fill="x", pady=5)

        tk.Label(self.file_frame, text="选择文件:").pack(side="left")
        self.file_entry = tk.Entry(self.file_frame, width=50)
        self.file_entry.pack(side="left", padx=5)

        self.browse_btn = tk.Button(self.file_frame, text="选择文件", command=self.select_file)
        self.browse_btn.pack(side="left")

        # 并发数量输入框
        self.concurrency_frame = tk.Frame(self)
        self.concurrency_frame.pack(fill="x", pady=5)

        tk.Label(self.concurrency_frame, text="并发数量:").pack(side="left")
        self.concurrency_entry = tk.Entry(self.concurrency_frame, width=10)
        self.concurrency_entry.pack(side="left", padx=5)
        self.concurrency_entry.insert(0, "3")  # 默认值

        # 启动按钮
        self.start_btn = tk.Button(self, text="开始执行", command=self.start_processing)
        self.start_btn.pack(pady=10)

        # 日志信息显示区域
        tk.Label(self, text="操作日志:").pack(anchor="w")
        self.log_area = scrolledtext.ScrolledText(self, height=10, width=70)
        self.log_area.pack(fill="both", expand=True)

        # 默认禁用日志编辑
        self.log_area.config(state="disabled")

        # ===== Template Section =====
        tk.Button(self, text="📝 打开模板文件", command=self.open_template_file).pack(pady=10)

    def open_template_file(self):
        """点击按钮后打开模板 Excel 文件"""
        # 构建模板路径
        template_name = "搜索-创建计划-样例.xlsx"
        if getattr(sys, 'frozen', False):  # 如果是打包后的程序
            base_path = sys._MEIPASS
            full_path = os.path.join(base_path, "shared", template_name)
        else:  # 开发环境
            full_path = os.path.abspath(os.path.join("..", "shared", template_name))

        # 检查文件是否存在
        if not os.path.exists(full_path):
            self.log(f"错误: 未找到模板文件 {full_path}", "red")
            return

        # 使用默认程序打开 Excel 文件
        try:
            if os.name == 'nt':  # Windows
                os.startfile(full_path)
            else:  # macOS / Linux
                import subprocess
                if sys.platform == 'darwin':
                    subprocess.call(['open', full_path])  # macOS
                else:
                    subprocess.call(['xdg-open', full_path])  # Linux
        except Exception as e:
            self.log(f"❌ 打开模板文件失败: {str(e)}", "red")

    def select_file(self):
        """打开文件选择对话框"""
        file_path = filedialog.askopenfilename(
            title="选择文件",
            filetypes=[("Excel文件", "*.xlsx")]
        )
        if file_path:
            self.file_path = file_path
            self.file_entry.delete(0, tk.END)
            self.file_entry.insert(0, file_path)
            self.log(f"已选择文件: {file_path}")

    def log(self, message, color="black"):
        """向日志区域添加消息"""
        self.log_area.config(state="normal")

        # 创建或复用标签
        tag_name = f"color_{color}"
        self.log_area.tag_configure(tag_name, foreground=color)

        self.log_area.insert(tk.END, message + "\n", tag_name)
        self.log_area.config(state="disabled")
        self.log_area.see(tk.END)  # 自动滚动到底部

    def start_processing(self):
        """启动处理按钮的回调函数"""
        # 获取用户输入
        self.file_path = self.file_entry.get()
        try:
            self.concurrency = int(self.concurrency_entry.get())
            if self.concurrency <= 0:
                raise ValueError("并发数必须大于0")
        except ValueError as e:
            self.log(f"错误: 并发数量必须是正整数 ({e})")
            return
        if not self.file_path:
            self.log("错误: 请先选择文件")
            return

        self.log(f"开始处理 - 文件: {self.file_path}, 并发数: {self.concurrency}")

        # start_sub_account_url(self.file_path, self.concurrency)
        thread = threading.Thread(
            target=start_sub_account_url,
            args=(self.file_path, self.concurrency),
            kwargs={'log_callback': self.log}  # 传递前端方法
        )
        thread.start()

        # 这里调用你的处理函数，例如:
        # process_file(self.file_path, self.concurrency)
        # 为了演示，我们模拟一个处理过程
        # self.simulate_processing()

if __name__ == "__main__":
    root = tk.Tk()
    app = Application(master=root)
    app.mainloop()